home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: more problems with qsort
- Date: Sat, 02 Mar 96 16:16:27 GMT
- Organization: none
- Message-ID: <825783387snz@genesis.demon.co.uk>
- References: <177399702S86.JW1675A@american.edu> <4h0j9e$ng5@clarknet.clark.net> <4h8bud$1vd@castle.nando.net>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <4h8bud$1vd@castle.nando.net>
- actuary@nando.net "Bill McCarthy" writes:
-
- >In <4h0j9e$ng5@clarknet.clark.net>,
- >yom@clark.net (yom) writes:
- >
- >>Since you're trying to sort a char**, the qsort function call must
- >>look like this:
- >>
- >>qsort(array,lines,sizeof(char **),(int (*)(void *,void *)) compare);
- >>
- >>And your compare function must be defined like this:
- >>
- >>int compare(char **a,char **b) {return strcmp(*a,*b);}
- >
- >Didn't you mean to type "sizeof( char * )" which, IMHO, could be
- >better expressed as "sizeof array[0]" ? Also, there's no need to
- >further complicate the call of qsort with the cast on compare if
- >you define compare() as:
-
- The code as written requires a diagnostic from the compiler (if stdlib.h
- is included) because the comparison function type takes const void * arguments
- and int (*)(void *, void *) is incompatible with
- int (*)(const void *, const void *).
-
- Even if the cast is fixed the code results in undefined behaviour since
- an int (char **, char **) function can't be legally called as an
- int (const void *, const void *) function which is how qsort() will call it.
-
- >int compare( const void *a, const void *b )
- >{
- > return strcmp( *(const char **)a, *(const char **)b );
- >}
-
- IMHO it is desirable to maintain corresponding consts where possible when
- casting so better would be:
-
- return strcmp( *(char *const *)a, *(char *const *)b );
-
- or
-
- return strcmp( *(const char *const *)a, *(const char *const *)b );
-
- which corresponds to writing it without casts as:
-
- int compare( const void *a, const void *b )
- {
- const char *const *a2 = a;
- const char *const *b2 = b;
-
- return strcmp( *a2, *b2 );
- }
-
- If nothing else it avoids compiler warnings such as:
- warning: cast discards `const' from pointer target type
-
- gcc agrees with me! :-)
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-